package io.github.cchenxi.crpc.simple.example.provider;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.github.cchenxi.crpc.core.api.RpcRequest;
import io.github.cchenxi.crpc.core.api.RpcResponse;
import io.github.cchenxi.crpc.core.provider.ProviderBootstrap;
import io.github.cchenxi.crpc.core.provider.ProviderConfig;
import io.github.cchenxi.crpc.core.provider.ProviderInvoker;

@SpringBootApplication
@RestController
@Import({ProviderConfig.class})
public class CrpcSimpleExampleProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrpcSimpleExampleProviderApplication.class, args);
    }

    @Autowired
    ProviderInvoker providerInvoker;

    /**
     * 使用HTTP+JSON实现通信和序列化
     *
     * @param rpcRequest 请求体
     * @return 返回
     */
    @RequestMapping("/")
    public RpcResponse<Object> invoke(@RequestBody RpcRequest rpcRequest) {
        return providerInvoker.invoke(rpcRequest);
    }

    @Bean
    ApplicationRunner providerRun() {
        return x -> {
            RpcRequest rpcRequest = new RpcRequest();
            rpcRequest.setService("io.github.cchenxi.crpc.simple.example.api.UserService");
            rpcRequest.setMethodSign("findById@1_int");
            rpcRequest.setArgs(new Object[]{1000});

            RpcResponse<Object> rpcResponse = invoke(rpcRequest);
            System.out.println("status=" + rpcResponse.isStatus() + ", data=" + rpcResponse.getData());

            RpcRequest rpcRequest1 = new RpcRequest();
            rpcRequest1.setService("io.github.cchenxi.crpc.simple.example.api.UserService");
            rpcRequest1.setMethodSign("findById@2_int_java.lang.String");
            rpcRequest1.setArgs(new Object[]{1000, "user01"});

            RpcResponse<Object> rpcResponse1 = invoke(rpcRequest1);
            System.out.println("status=" + rpcResponse1.isStatus() + ", data=" + rpcResponse1.getData());
        };
    }
}
